import React, { useReducer, useEffect } from "react";
import query from "../../api/query";
import AsyncStorage from "@react-native-async-storage/async-storage";

const InterviewSpeedAuditorContext = React.createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "fetch_init":
      return action.payload;
    case "add_interviewSpeed":
      return [...state, action.payload];
    default:
      return state;
  }
};

export const InterviewSpeedAuditorProvider = ({ children }) => {
  const [InterviewSpeedList, dispatch] = useReducer(dataReducer, []);

  useEffect(() => {
    getAllInterviewSpeed();
  }, []);

  const getAllInterviewSpeed = async () => {
    try {
      //1、获得所有的访谈记录
      const token = await AsyncStorage.getItem("token");
      const result = await query.get("/interview/", {
        headers: { Authorization: token },
      });
      let allinterview = result.data.data;
      //2、将同一天访谈记录放在一个数组里
      let interviewByDay = Object.values(
        allinterview.reduce((res, item) => {
          res[item.date]
            ? res[item.date].push(item)
            : (res[item.date] = [item]);
          return res;
        }, {})
      );
      //3、构造访谈进度
      let interviewSpeed = interviewByDay.map((interview) => {
        let speedData = {
          group: "",
          time: "",
          municipalInterview: 0,
          countyInterview: 0,
          townshipInterview: 0,
          villageInterview: 0,
          contactTalk: 0,
          resettlementInterview: 0,
          municipalLeaders: 0,
          municipalDepartment: 0,
          countyLeaders: 0,
          countyDepartment: 0,
          townshipLeaders: 0,
          villageCadres: 0,
          villageDoctorsAndPrincipals: 0,
          firstSecretary: 0,
          NPCdeputies: 0,
        };
        interview.map((item) => {
          switch (item.type) {
            case "市级访谈":
              speedData.municipalInterview++;
              break;
            case "县级访谈":
              speedData.countyInterview++;
              break;
            case "镇级访谈":
              speedData.townshipInterview++;
              break;
            case "村级访谈":
              speedData.villageInterview++;
              break;
            case "对接会讲话":
              speedData.contactTalk++;
              break;
            case "安置点访谈":
              speedData.resettlementInterview++;
              break;
            default:
              break;
          }
          speedData.municipalLeaders += item.municipalLeaders;
          speedData.municipalDepartment += item.municipalDepartment;
          speedData.countyLeaders += item.countyLeaders;
          speedData.countyDepartment += item.countyDepartment;
          speedData.townshipLeaders += item.townshipLeaders;
          speedData.villageCadres += item.villageCadres;
          speedData.villageDoctorsAndPrincipals +=
            item.villageDoctorsAndPrincipals;
          speedData.firstSecretary += item.firstSecretary;
          speedData.NPCdeputies += item.NPCdeputies;
          speedData.time = item.date;
          speedData.group += item.publisher.group;
        });
        let quchonggroup = "";
        for (var i = 0; i < speedData.group.length; i++) {
          if (quchonggroup.indexOf(speedData.group.charAt(i)) == -1) {
            quchonggroup += speedData.group.charAt(i) + ",";
          }
        }
        speedData.group = quchonggroup.slice(0, quchonggroup.length - 1);
        return speedData;
      });
      const sortInterviewSpeed = interviewSpeed.sort((a, b) => {
        return a.time < b.time ? 1 : -1;
      });
      dispatch({ type: "fetch_init", payload: sortInterviewSpeed });
    } catch (err) {
      console.log("获取所有访谈进度失败", err);
    }
  };

  const updateSpeed = async (group, setIsLoading) => {
    try {
      //1、获得所有的访谈记录
      const token = await AsyncStorage.getItem("token");
      const result = await query.get("/interview/", {
        headers: { Authorization: token },
      });
      let allinterview = result.data.data;
      let tag = 0;
      //2.筛选分组
      if (group != "全部") {
        tag = 1;
        allinterview = allinterview.filter(
          (item) => item.publisher.group === group
        );
      }
      //3、将同一天访谈记录放在一个数组里
      let interviewByDay = Object.values(
        allinterview.reduce((res, item) => {
          res[item.date]
            ? res[item.date].push(item)
            : (res[item.date] = [item]);
          return res;
        }, {})
      );
      //4、构造访谈进度
      let interviewSpeed = interviewByDay.map((interview) => {
        let speedData = {
          group: "",
          province: "",
          city: "",
          time: "",
          municipalInterview: 0,
          countyInterview: 0,
          townshipInterview: 0,
          villageInterview: 0,
          contactTalk: 0,
          resettlementInterview: 0,
          municipalLeaders: 0,
          municipalDepartment: 0,
          countyLeaders: 0,
          countyDepartment: 0,
          townshipLeaders: 0,
          villageCadres: 0,
          villageDoctorsAndPrincipals: 0,
          firstSecretary: 0,
          NPCdeputies: 0,
        };
        interview.map((item) => {
          switch (item.type) {
            case "市级访谈":
              speedData.municipalInterview++;
              break;
            case "县级访谈":
              speedData.countyInterview++;
              break;
            case "镇级访谈":
              speedData.townshipInterview++;
              break;
            case "村级访谈":
              speedData.villageInterview++;
              break;
            case "对接会讲话":
              speedData.contactTalk++;
              break;
            case "安置点访谈":
              speedData.resettlementInterview++;
              break;
            default:
              break;
          }
          speedData.municipalLeaders += item.municipalLeaders;
          speedData.municipalDepartment += item.municipalDepartment;
          speedData.countyLeaders += item.countyLeaders;
          speedData.countyDepartment += item.countyDepartment;
          speedData.townshipLeaders += item.townshipLeaders;
          speedData.villageCadres += item.villageCadres;
          speedData.villageDoctorsAndPrincipals +=
            item.villageDoctorsAndPrincipals;
          speedData.firstSecretary += item.firstSecretary;
          speedData.NPCdeputies += item.NPCdeputies;
          speedData.group += item.publisher.group;
          speedData.province = item.province;
          speedData.city = item.city;
          speedData.time = item.date;
        });
        if (tag == 0) {
          let quchonggroup = "";
          for (var i = 0; i < speedData.group.length; i++) {
            if (quchonggroup.indexOf(speedData.group.charAt(i)) == -1) {
              quchonggroup += speedData.group.charAt(i) + ",";
            }
          }
          speedData.group = quchonggroup.slice(0, quchonggroup.length - 1);
        } else {
          speedData.group = speedData.group.slice(0, 1);
        }
        return speedData;
      });
      const sortInterviewSpeed = interviewSpeed.sort((a, b) => {
        return a.time < b.time ? 1 : -1;
      });
      dispatch({ type: "fetch_init", payload: sortInterviewSpeed });
      setIsLoading();
    } catch (err) {
      setIsLoading();
      console.log("更新访谈进度失败", err);
    }
  };

  return (
    <InterviewSpeedAuditorContext.Provider
      value={{
        interviewSpeedList: InterviewSpeedList,
        updateSpeed,
      }}
    >
      {children}
    </InterviewSpeedAuditorContext.Provider>
  );
};

export default InterviewSpeedAuditorContext;
